package com.ccnu.JobHub.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccnu.JobHub.common.util.Token;
import com.ccnu.JobHub.model.common.Result;
import com.ccnu.JobHub.model.database.Student;
import com.ccnu.JobHub.model.database.Verification;
import com.ccnu.JobHub.model.request.PostVerificationRequest;
import com.ccnu.JobHub.model.request.PutVerificationRequest;
import com.ccnu.JobHub.service.impl.StudentService;
import com.ccnu.JobHub.service.impl.VerificationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("authority")
@CrossOrigin("*")
@Slf4j
public class AuthorityController {
    private final VerificationService verificationService;
    private final StudentService studentService;

    @Value("${upload.verification}")
    private String uploadDir;

    /**
     * 构造函数
     * @param verificationService 注入这个服务
     */
    public AuthorityController(VerificationService verificationService, StudentService studentService) {
        this.verificationService = verificationService;
        this.studentService = studentService;
    }

    /**
     * 发送权限二次认证
     * @param token token令牌
     * @param postVerificationRequest 证明材料
     * @return 一个Result结果
     */
    @PostMapping("verification")
    public Result verification(@RequestHeader("token") String token, @RequestBody PostVerificationRequest postVerificationRequest){
        log.info("--------------------申请二次认证请求--------------------");
        Integer studentId = Integer.valueOf(Token.inspectOldToken(token));
        QueryWrapper<Verification> verificationQueryWrapper = new QueryWrapper<Verification>()
                .eq("student_id",studentId);
        if(verificationService.getOne(verificationQueryWrapper) != null){
            return Result.error("当前用户已申请过二次认证");
        }
        Verification verification = new Verification();
        try {
            // 将Base64数据解码为二进制数据
            byte[] verificationImageData = Base64.decodeBase64(postVerificationRequest.getVerificationImage());

            String fileName = UUID.randomUUID() + ".jpg";
            Path uploadPath = Paths.get(uploadDir, fileName);

            Files.createDirectories(uploadPath.getParent());

            // 将解码后的数据写入文件

            Files.write(uploadPath, verificationImageData);

            verification.setPosition(postVerificationRequest.getPosition());
            verification.setContact(postVerificationRequest.getContact());
            verification.setCompanyName(postVerificationRequest.getCompanyName());
            verification.setCompanyAddress(postVerificationRequest.getCompanyAddress());
            verification.setContent(postVerificationRequest.getContent());
            verification.setStudentId(studentId);
            verification.setVerificationImage(uploadPath.toString());
            verificationService.save(verification);

            return Result.success("申请二次认证成功");
        } catch (IOException e) {
            log.error(String.valueOf(e));
            return Result.error("申请二次认证失败");
        }
    }

    /**
     * 获取待审核的二次认证
     * @param page 当前页码
     * @param pageSize 页面大小
     * @return 返回一个Result结果
     */
    @GetMapping("verification")
    public Result verification(@RequestParam("page") Integer page, @RequestParam("pageSize") Integer pageSize){
        log.info("--------------------获取待审核二次认证请求--------------------");
        Page<Verification> page1 = Page.of(page,pageSize);
        List<Verification> verifications = verificationService.list(page1);
        if (verifications.isEmpty()){
            return Result.error("当前无待审核的二次认证申请");
        }
        for (Verification verification : verifications){
            Student student = studentService.getById(verification.getStudentId());
            verification.setName(student.getName());
//            verification.setAvatar(student.getAvatar());
        }
        return Result.success("成功获取待审核二次认证",verifications);
    }

    /**
     * 查看二次认证材料
     * @param verificationId 对应的verification表的主键id
     * @return 一个Result结果
     */
    @GetMapping("getVerificationImage")
    public Result getVerificationImage(@RequestParam("verificationId") String verificationId){
        log.info("--------------------查看二次认证材料请求--------------------");
        Verification verification = verificationService.getById(verificationId);
        if (verification == null){
            return Result.error("不存在该申请");
        }
        Path filePath = Paths.get(verification.getVerificationImage());
        try {
            // 读取图片文件的输入流
            String base64Image;
            try (InputStream imageStream = Files.newInputStream(filePath)) {
                // 将图片文件转换为Base64字符串
                base64Image = Base64.encodeBase64String(imageStream.readAllBytes());
            }

            // 返回 Result 对象
            return Result.success("返回二次认证材料成功", base64Image);
        } catch (IOException e) {
            // 处理异常，例如图片不存在时的情况
            log.error(String.valueOf(e));
            return Result.error("返回二次认证材料失败");
        }
    }

    /**
     * 审核二次认证
     * @param putVerificationRequest 包含verificationId,和是否通过审批
     * @return 返回一个Result结果
     */
    @PutMapping("verification")
    public Result verification(@RequestBody PutVerificationRequest putVerificationRequest){
        log.info("--------------------审核二次认证请求--------------------");
        Verification verification = verificationService.getById(putVerificationRequest.getVerificationId());
        System.out.println(verification);
        if (verification==null){
            return Result.error("不存在该申请");
        }
        Student student = studentService.getById(verification.getStudentId());
        if (putVerificationRequest.getFlag().equals(1)){
            student.setAuthority(1);
            student.setPosition(verification.getPosition());
            student.setCurrentCompany(verification.getCompanyName());
            studentService.saveOrUpdate(student);
        }
        Path path = Paths.get(verification.getVerificationImage());
        try {
            Files.delete(path);
        } catch (IOException e) {
            System.out.println("文件删除失败: " + e.getMessage());
            return Result.error("申请材料删除失败");
        }
        verificationService.removeById(verification);
        return Result.success("审核二次认证申请成功");
    }
}
